package com.chia.multienty.core.infra.filter;

import com.alibaba.fastjson.JSONObject;
import com.chia.multienty.core.domain.constants.MultientyHeaderConstants;
import com.chia.multienty.core.properties.yaml.YamlMultientyProperties;
import com.chia.multienty.core.tools.MultientyContext;
import com.chia.multienty.core.util.SpringUtil;
import io.jsonwebtoken.lang.Strings;
import io.seata.core.context.RootContext;
import io.seata.core.model.BranchType;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

@Activate(group = CommonConstants.CONSUMER)
@Slf4j
public class MultientyDubboConsumerFilter implements Filter {
    private YamlMultientyProperties properties;
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if(properties == null) {
            properties = SpringUtil.getBean(YamlMultientyProperties.class);
        }
        // 在请求前附带http header
        if (MultientyContext.getMppAppId() != null) {
            invocation.setAttachment(MultientyHeaderConstants.MPP_APP_ID_KEY, MultientyContext.getMppAppId().toString());
        }
        if(Strings.hasText(MultientyContext.getToken())) {
            invocation.setAttachment(MultientyHeaderConstants.TOKEN_KEY, MultientyContext.getToken());
        }
        if(MultientyContext.getAppType() != null) {
            invocation.setAttachment(MultientyHeaderConstants.APP_ID_KEY, MultientyContext.getAppType().getValue().toString());
        }
        if (MultientyContext.getProgramId() != null) {
            invocation.setAttachment(MultientyHeaderConstants.PROGRAM_ID_KEY, MultientyContext.getProgramId().toString());
        }
        if (MultientyContext.getTenant() != null) {
            invocation.setAttachment(MultientyHeaderConstants.TENANT_ID_KEY, MultientyContext.getTenant().getTenantId().toString());
        }
        if(MultientyContext.getActivityId() != null) {
            invocation.setAttachment(MultientyHeaderConstants.ACT_ID_KEY, MultientyContext.getActivityId().toString());
        }

        String xid = RootContext.getXID();
        BranchType branchType = RootContext.getBranchType();

        if (log.isDebugEnabled()) {
            log.debug(String.format("Client side xid in RootContext[%s]", xid));
        }
        if (xid != null) {
            invocation.setAttachment(RootContext.KEY_XID, xid);
            if (branchType != null) {
                invocation.setAttachment(RootContext.KEY_BRANCH_TYPE, branchType.name());
            }
        }
        if(properties.getShowDebug()) {
            log.info("Dubbo Consumer Header Migration:{}", JSONObject.toJSONString(invocation.getAttachments(), true));
        }
        Result result = invoker.invoke(invocation);
        return result;
    }

}
